﻿using Microsoft.EntityFrameworkCore;
using ZenSystemService.Api.Data;
using ZenSystemService.Api.Entities;

namespace ZenSystemService.Api.Services
{
    public class UserRoleService
    {
        private readonly ApplicationDbContext _context;

        public UserRoleService(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<IEnumerable<Role>> GetUserRolesAsync(int userId)
        {
            try
            {
                return await _context.UserRoles
                    .Where(ur => ur.UserId == userId)
                    .Select(ur => ur.Role)
                    .ToListAsync();
            }
            catch(Exception ex)
            {
                return null;
            }
        }

        public async Task<bool> AssignRoleToUserAsync(int userId, int roleId)
        {
            if (!await _context.UserRoles.AnyAsync(ur => ur.UserId == userId && ur.RoleId == roleId))
            {
                _context.UserRoles.Add(new UserRole { UserId = userId, RoleId = roleId });
                int count = await _context.SaveChangesAsync();
                return count > 0 ? true : false;
            }
            return false;
        }

        public async Task RemoveRoleFromUserAsync(int userId, int roleId)
        {
            var userRole = await _context.UserRoles.SingleOrDefaultAsync(ur => ur.UserId == userId && ur.RoleId == roleId);
            if (userRole != null)
            {
                _context.UserRoles.Remove(userRole);
                await _context.SaveChangesAsync();
            }
        }
    }
}